package service

import (
	"errors"
	uuid "github.com/satori/go.uuid"
	"go_shengshu_admin/model"
	"go_shengshu_admin/query"
	"go_shengshu_admin/repository"
	"go_shengshu_admin/utils"
)

type UserService struct {
	Repo *repository.UserRepository
}

type UserSer interface {
	List(req *query.ListQuery) (users []*model.User, err error)
	GetTotal() (total int64, err error)
	Get(User model.User) (user *model.User, err error)
	Exist(User model.User) *model.User
	ExistByUserId(user model.User) *model.User
	ExistByMobile(user model.User) *model.User
	Add(user model.User) (*model.User, error)
	Edit(user model.User) (bool, error)
	Delete(id string) (bool, error)
}

func (srv *UserService) List(req *query.ListQuery) (users []*model.User, err error) {
	return srv.Repo.List(req)
}

func (srv *UserService) GetTotal() (total int64, err error) {
	return srv.Repo.GetTotal()
}

func (srv *UserService) Get(User model.User) (user *model.User, err error) {
	return srv.Repo.Get(User)
}

func (srv *UserService) Exist(User model.User) *model.User {
	return srv.Repo.Exist(User)
}

func (srv *UserService) ExistByUserId(user model.User) *model.User {
	return srv.Repo.ExistByUserId(user.UserId)
}

func (srv *UserService) ExistByMobile(user model.User) *model.User {
	return srv.Repo.ExistByMobile(user)
}

func (srv *UserService) Add(user model.User) (*model.User, error) {
	if srv.Repo.ExistByMobile(user) != nil {
		return nil, errors.New("用户已存在")
	}
	user.UserId = uuid.NewV4().String()
	if user.Password == "" {
		user.Password = utils.Md5("123456")
	} else {
		user.Password = utils.Md5(user.Password)
	}
	user.IsDeleted = false
	user.IsLocked = false
	return srv.Repo.Add(user)
}

func (srv *UserService) Edit(user model.User) (bool, error) {
	if user.UserId == "" {
		return false, errors.New("参数错误") //安全方面，不可提供太多信息回去
	}
	if srv.Repo.ExistByUserId(user.UserId) != nil {
		return false, errors.New("用户不存在")
	}
	return srv.Repo.Edit(user)
}

func (srv *UserService) Delete(id string) (bool, error) {
	if id == "" {
		return false, errors.New("参数错误")
	}
	if srv.Repo.ExistByUserId(id) != nil {
		return false, errors.New("用户不存在")
	}
	return srv.Repo.Delete(id)
}
